package me.minecraft.plugin.playerride.listener;

import me.minecraft.plugin.playerride.manager.MainManager;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerInteractEntityEvent;
import org.bukkit.inventory.EquipmentSlot;

/**
 * @author langle__
 * @version 1.0
 */
public class PlayerEvent implements Listener {

    @EventHandler
    public void onPlayerInteractEntity(PlayerInteractEntityEvent event) {
        Player player = event.getPlayer();
        EquipmentSlot hand = event.getHand();
        Entity entity = event.getRightClicked();

        if (hand != EquipmentSlot.HAND || entity.getType() != EntityType.PLAYER) return;
        if (!(entity instanceof Player)) return;
        Player target = (Player) entity;

        if (!MainManager.INSTANCE.hasRiderTarget(player)) return;

        if (MainManager.INSTANCE.isProtected(target)) {
            player.sendMessage("[§c玩家骑乘§f] 玩家 " + target.getName() + " 已开启保护模式，无法骑乘");
            MainManager.INSTANCE.removeRiderTarget(player);
            return;
        }

        Player riderTarget = MainManager.INSTANCE.getRiderTarget(player);
        if (riderTarget == null) {
            player.sendMessage("[§a玩家骑乘§f] 玩家不存在");
            return;
        }

        if (player != riderTarget) {
            player.sendMessage("[§a玩家骑乘§f] " + riderTarget.getName() + " 正在骑乘 " + target.getName());
        } else {
            player.sendMessage("[§a玩家骑乘§f] 正在骑乘玩家: " + target.getName());
        }

        target.addPassenger(riderTarget);
        MainManager.INSTANCE.removeRiderTarget(player);
    }

}
